import os
from threading import Thread

from flask_cors import CORS
from flask import Flask, request, jsonify, make_response

from DB import Session
from WbEntity import WbImageUrl
from WbRun import down_image, get_uid_name
from WbMysql import insert_image_url_bulk, execute_query, execute_update
import requests
from LocalWb import app1

app = Flask(__name__)
CORS(app)


# 如果只想允许特定的来源，例如 'http://127.0.0.1:3000'，可以这样设置：
# CORS(app, resources={r"/*": {"origins": "http://127.0.0.1:3000"}})
@app.route('/proxy_image')
def proxy_image():
    image_url = request.args.get('url')
    if not image_url:
        return "No URL provided", 400

        # 发送请求到第三方图片地址
    response = requests.get(image_url, allow_redirects=True)
    # 检查请求是否成功
    if response.status_code == 200:
        # 创建 Response 对象
        res = make_response(response.content)
        # 设置内容类型
        res.headers['Content-Type'] = response.headers.get('Content-Type', 'application/octet-stream')
        return res
    else:
        return f"Error fetching image: {response.status_code}", response.status_code


@app.route('/save/wb', methods=['get'])
def save_wb():
    uid = request.args.get('uid')
    type1 = request.args.get('type')
    if type1 == '1':
        thread = Thread(target=down_image, args=(uid, type1))
        thread.start()
    else:
        count = down_image(uid, type1)
        return jsonify({"count": count}), 202

    return jsonify({"message": "Download started!"}), 202


@app.route('/get_uid_list', methods=['get'])
def get_uid_list():
    distinct_uids = execute_query("SELECT DISTINCT uid,uidName FROM wb_image_url")
    uid_list = [{"uid": row[0], "uidName": row[1]} for row in distinct_uids]
    return jsonify({
        "list": uid_list
    }), 200


@app.route('/delete_image', methods=['get'])
def delete_wb():
    id = request.args.get('id')
    session = Session()
    try:
        deleted_count = session.query(WbImageUrl).filter_by(id=id).delete()
        session.commit()
        if deleted_count > 0:
            return {"message": "删除成功"}, 200
        else:
            return {"message": "未找到该记录"}, 404
    except Exception as e:
        session.rollback()  # 如果出现异常，回滚事务
        return {"message": f"删除失败: {str(e)}"}, 500

    finally:
        session.close()  # 关闭会话


@app.route('/get_images', methods=['GET'])
def get_images():
    start_page = request.args.get('page', default=0, type=int)  # 获取开始页
    end_page = request.args.get('size', default=10, type=int)
    session = Session()
    uid = request.args.get('uid', default=None, type=str)  # 获取 uid 参数
    try:
        query = session.query(WbImageUrl)
        # 根据 uid 进行过滤
        if uid:
            query = query.filter(WbImageUrl.uid == uid)
        total_count = query.count()
        images = query.offset(start_page * end_page).limit(end_page).all()  # 分页查询
        result = [{"id": img.id, "realurl": img.realurl, "pathUrl": img.pathUrl, "uid": img.uid} for img in images]
        # 计算总页数
        total_pages = (total_count // end_page) + (1 if total_count % end_page > 0 else 0)
        return jsonify({
            "total": total_count,
            "total_pages": total_pages,  # 返回总页数
            "images": result  # 返回图片数据
        }), 200
    except Exception as e:
        return jsonify({"message": "查询失败", "error": str(e)}), 500
    finally:
        session.close()


@app.route('/wb_transfer', methods=['GET'])
def wb_transfer():
    image_file = "C:\\Users\\Administrator\\Desktop\\wb"
    images = os.listdir(image_file)
    image_data_list = []
    for image in images:
        print(image)
        new_image = WbImageUrl(realurl=image, pathUrl=image, uid="def", uidName="def")

        image_data_list.append(new_image)
    print(len(image_data_list))
    insert_image_url_bulk(image_data_list)
    return jsonify({"message": "wb_transfer started!"}), 200


@app.route('/update_uid_name', methods=['GET'])
def update_uid_name():
    uid = request.args.get('uid', default=None, type=str)
    uid_name = get_uid_name(uid)
    # updated_count = session.query(WbImageUrl).filter(WbImageUrl.uid == uid).update(
    #     {WbImageUrl.pathUrl: new_pathurl}
    # )
    if uid_name:
        sql = f"UPDATE wb_image_url SET uidName='{uid_name}' WHERE uid='{uid}'"
        result = execute_update(sql)
        print(result)
        return uid_name, 200
    else:
        return "uid 无法获取", 200

app.register_blueprint(app1)

if __name__ == '__main__':
    app.run(host='0.0.0.0', debug=True, port=9001)
